#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2021-1-3 9:55
# @file     : crontab_fund.py
# @Software : PyCharm
# ======================================#
import os
import sys
import time
from collections import defaultdict

from config import BASE_DIR, DING_TOKEN_FOCUS, DING_TOKEN_TIP, DING_TOKEN_AI
from src.core.fund import Fund
from src.tools.ding import send_text
from src.tools.parse import ParseConf


def fund_TOP_ok(top=25):
    def out(data_list):
        for data in data_list:
            code = data[0]
            code_name = data[1]
            output_info(code, code_name, skip=True)

    f = Fund()
    out(f.fund_GP(top=top))
    out(f.fund_HH(top=top))
    out(f.fund_ZS(top=top))
    out(f.fund_ETF(top=top))
    out(f.fund_FOF(top=top))
    # out(f.fund_ZQ(top=top))
    # out(f.fund_QDII(top=top))
    out(f.fund_LOF(top=top))


def fund_AI(top=75):
    f = Fund()
    f.fund_ALL(top=top, skip=False)
    f.output_classify_detail()


def fund_TOP(top=10):
    f = Fund()
    f.fund_ALL(print=True)
    f.fund_ETF(top=top, print=True)
    f.fund_FOF(top=top, print=True)
    f.fund_GP(top=top, print=True)
    f.fund_HH(top=top, print=True)
    f.fund_ZQ(top=top, print=True)
    f.fund_ZS(top=top, print=True)
    f.fund_QDII(top=top, print=True)
    f.fund_LOF(top=top, print=True)


def fund_FOCUS():
    path_file = os.path.join(BASE_DIR, "src/conf/fund.ini")
    if sys.platform.startswith("win"):
        path_file = path_file.replace("/", "\\")
    parse = ParseConf(path_file)
    my_fund = parse.get_section_info("my_fund")

    for code, code_name in my_fund.items():
        output_info(code, code_name)


def get_up_up_fund(y1=120, m6=90, m3=60, m1=20, week=10, per=1.3):
    f = Fund()
    collect = f.get_all_fund_increate_down_info(pn=10000)
    allup = defaultdict(list)
    for key, value in collect.items():
        if sum(value[0:5]) > y1 * per:
            allup[key] = value
        elif sum(value[0:4]) > m6 * per:
            allup[key] = value
        elif sum(value[0:3]) > m3 * per:
            allup[key] = value
        elif sum(value[0:2]) > m1 * per:
            allup[key] = value
        elif sum(value[0:1]) > week * per:
            allup[key] = value
    title = "最近一周,一月,三月,半年,一年涨的较多基金"
    content = ""
    for key, value in allup.items():
        code, name = key.split(":")
        content += f"{key} {value}\n"
        # output_info(code, name,send_ding=False)
    send_text(title, content, DING_TOKEN_AI)


def get_down_down_fund(y1=-40, m6=-25, m3=-15, m1=-10, week=-5, per=0.8):
    f = Fund()
    collect = f.get_all_fund_increate_down_info(pn=10000)
    # print("近1周 近1月到近1周 近3月到近1月 近6月到近3月 近1年到近3月 近两年到近一年 近3年到近2年")
    # print("一周 一月 三月 六月 一年 两年 三年")
    downdown = defaultdict(list)
    summ = 0
    tj = 0
    for key, value in collect.items():
        # if "债" in key: continue
        if sum(value[0:5]) < y1 * per:
            downdown[key] = value
            summ += value[0]
            tj += 1
        elif sum(value[0:4]) < m6 * per:
            downdown[key] = value
            summ += value[0]
            tj += 1
        elif sum(value[0:3]) < m3 * per:
            downdown[key] = value
            summ += value[0]
            tj += 1
        elif sum(value[0:2]) < m1 * per:
            downdown[key] = value
            summ += value[0]
            tj += 1
        elif sum(value[0:1]) < week * per:
            downdown[key] = value
            summ += value[0]
            tj += 1

    title = f"最近一周,一月,三月,半年,一年跌的较多均值涨幅： {round(summ / tj, 2)}"
    content = ""
    for key, value in downdown.items():
        code, name = key.split(":")
        content += f"{key} {value}\n"
        # output_info(code, name,send_ding=False)
    print(content)
    send_text(title, content, DING_TOKEN_AI)


def output_info(code, code_name, skip=False, send_ding=True):
    def bool_info(per, percent=10, revers=False):
        try:
            per = float(per[0:-1])
            if revers:
                if per < percent:
                    return 1
                else:
                    return 0
            else:
                if per > percent:
                    return 1
                else:
                    return 0
        except:
            return 0

    f = Fund()
    f_info, g_info, z_info = f.fund_info(code)
    title = f"{code}:{code_name} {'  '.join(list(f_info.values()))}"
    content = ""
    text = ""
    gp = {"syl": 0, "mlv": 0, "jlv": 0, "zb": 0, "zbi": 0, "hsl": 0}
    zq = 0
    if g_info:
        content += "【股票】\n"
        tag = True
        i = 0.001
        for g, info in g_info.items():
            if "industry" in info.keys():
                industry = info.pop("industry")
            else:
                industry = "other"
            try:
                info.pop("code")
                info.pop("持股")
                info.pop("持股市值")
                info.pop("总资产")
                info.pop("净资产")
                info.pop("净利润")
                info.pop("流出")
            except:
                pass
            if tag:
                tag = False
                content += '   '.join(info.keys()) + "\n"
            content += f"[{industry}]:\n" + "  ".join(info.values()) + "\n"
            # 分析统计
            if "市盈率" not in info.keys(): info["市盈率"] = 0
            if "毛利率" not in info.keys(): info["毛利率"] = 0
            if "净利率" not in info.keys(): info["净利率"] = 0

            gp["syl"] += bool_info(info["市盈率"], 30, revers=True)  # 越低越好
            gp["mlv"] += bool_info(info["毛利率"], 30)
            gp["jlv"] += bool_info(info["净利率"], 15)
            try:
                per = float(info["占比"][0:-1])
                rate = float(info["增率"][0:-1])
                gp["zb"] += per
                gp["zbi"] += (per * rate) / 100
                gp["hsl"] += float(info["换手率"][0:-1])
                i += 1
            except:
                pass
        if gp["zb"] == 0:
            zbl = 0
        else:
            zbl = round(100 * gp['zbi'] / gp['zb'], 4)
        text += f"股票占比: {round(gp['zb'], 2)}% 换手率: {round(gp['hsl'] / i, 2)}% 增率: {round(gp['zbi'], 3)}% 预测: {zbl}%\n"
        content += f"股票占比: {round(gp['zb'], 2)}% 换手率: {round(gp['hsl'] / i, 2)}% 增率: {round(gp['zbi'], 3)}% 预测: {zbl}%\n"
    if z_info:
        content += "【债券】\n"
        tag = True
        for z, info in z_info.items():
            if tag:
                tag = False
                content += '    '.join(info.keys()) + "\n"
            content += "  ".join(info.values()) + "\n"
            try:
                zq += float(info["占比"][0:-1])
            except:
                pass
        text += f"债券占比: {round(zq, 3)}%\n"
        content += f"债券占比: {round(zq, 3)}%\n"
    reason = gp["jlv"] + gp["mlv"]
    zs1 = round(reason * 100 / 20, 2)
    reason += gp["syl"]
    zs2 = round(reason * 100 / 30, 2)

    text += f"【购买指数:{zs2}%  {zs1}%】 市盈30:{gp['syl']} 毛利30:{gp['mlv']} 净利15:{gp['jlv']}"
    if send_ding:
        send_text(title, content, DING_TOKEN_FOCUS)
        time.sleep(6)
        send_text(title, text, DING_TOKEN_TIP)
        time.sleep(6)
    else:
        if gp['zb'] > 30:
            print(f"{title}\n{text}")


def run(run_type="top"):
    if run_type == "top":
        fund_TOP()
    elif run_type == "focus":
        fund_FOCUS()
    elif run_type == "AI":
        fund_AI(top=1)
    elif run_type == "top_AI":
        fund_TOP_ok(top=1)
    elif run_type == "Down":
        get_down_down_fund(per=0.9)
    elif run_type == "Up":
        get_up_up_fund()


if __name__ == "__main__":
    # run(run_type="focus")
    # run(run_type="Down")
    fund_FOCUS()
